package cn.com.cfae.iras.doc.analyze.parse.extractor;

import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.parse.model.*;
import cn.com.cfae.iras.doc.analyze.parse.tokenizer.MJZJYTTokenizer;
import cn.com.cfae.iras.doc.analyze.parse.tokenizer.YXZWTokenizer;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.soap.Text;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class M4Extractor extends MTableExtractor {
    private static final Logger logger = LoggerFactory.getLogger(M4Extractor.class);

    MJZJYTTokenizer mjzjytTokenizer = MJZJYTTokenizer.getInstance();
    YXZWTokenizer yxzwTokenizer = YXZWTokenizer.getInstance();

    @Override
    public void extract() {
        try {
            extractM4();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    private void extractM4() {
        long t1 = System.currentTimeMillis();
        logger.info("开始抽取：{}章节业务模型数据，表格类型：{}......", getChapterModel().getChapterId(), getChapterModel().getTableItem().getItemName(), getDocumentModel().getTableType());
        try {
            parseChapterSection();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        try {
            extractM4Mjzjyt();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        long t2 = System.currentTimeMillis();
        logger.info("抽取：{}章节业务模型数据完成，表格类型：{}，耗时：{}毫秒。", getChapterModel().getChapterId(), getChapterModel().getTableItem().getItemName(), getDocumentModel().getTableType(), (t2 - t1));
    }

    /**
     * 有息债务
     */
    private void extractM4Yxzw2() {
        long t1 = System.currentTimeMillis();
        logger.info("开始抽取：{}章有息债务业务模型数据......", getChapterModel().getChapterId());
        List<PageModel> pageModelList = getPageModelList();
        PageModel pageModel = null;
        List<PageArea> pageAreaList = new ArrayList<>();
        TextLayout startTextLayout = null;
        TextLayout endTextLayout = null;
        for (int i = 0; i < pageModelList.size(); i++) {
            pageModel = pageModelList.get(i);
            if (pageModel == null) {
                continue;
            }
            JsonArray itemArray = getPageDataArray(pageModel);
            for (int j = 0; j < itemArray.size(); j++) {
                JsonArray items = itemArray.get(j).getAsJsonArray();
                String combineLine = combineTextJsonArray(items);
                if (isEmpty(combineLine)) {
                    continue;
                }
                if (j == (itemArray.size() - 1)) {
                    if (getPageModelBottomPageNum(items) > 0) {
                        logger.info("抽取：{}章有息债务业务模型数据，当前页码：{}，在建工程信息表跳页，到下一页定位在建工程信息表结束位置。", getChapterModel().getChapterId(), pageModel.getPageNumber());
                        break;
                    }
                }
                if (isYXZW(combineLine)) {
                    if (startTextLayout != null) {
                        endTextLayout = createKVTextLayout(pageModel, items);
                        logger.info("抽取：{}章有息债务业务模型数据，分析定位到在建工程表格结束位置，结束页码：{}。", getChapterModel().getChapterId(), combineLine);
                        pageAreaList.addAll(createPageArea(startTextLayout, endTextLayout));
                        startTextLayout = null;
                        endTextLayout = null;
                    }
                    logger.info("抽取：{}章有息债务业务模型数据，开始页码：{}，分析定位到在建工程表格位置......，表头信息：{}。", getChapterModel().getChapterId(), combineLine);
                    startTextLayout = createKVTextLayout(pageModel, items);
                    continue;
                }
                if (isInner3(items, pageModel)) {
                    continue;
                } else if (startTextLayout != null) {
                    if (isAmtUnit(combineLine)) {
                        continue;
                    }
                    endTextLayout = createKVTextLayout(pageModel, items);
                    logger.info("抽取：{}章在建工程业务模型数据，分析定位到在建工程表格结束位置，结束页码：{}。", getChapterModel().getChapterId(), combineLine);
                    pageAreaList.addAll(createPageArea(startTextLayout, endTextLayout));
                    startTextLayout = null;
                    endTextLayout = null;
//                    if (isZJXM(combineLine)) {
//                        startTextLayout = createKVTextLayout(pageModel, items.get(0).getAsJsonObject());
//                    }
                    continue;
                }
            }
        }
        if (CollectionUtils.isEmpty(pageAreaList)) {
            logger.info("抽取：{}章有息债务业务模型数据，分析定位在建工程表格位置失败。", getChapterModel().getChapterId());
            return;
        }
        logger.info("抽取：{}章有息债务业务模型数据，在建工程表格位置定位完成，开始抽取模型数据......", getChapterModel().getChapterId());
        ExtractBizModel extractBizModel = getChapterModel().getExtractBizModelMap().get("YXZW");
        yxzwTokenizer.loadCoreSynonyms(extractBizModel);
        for (int i = 0; i < pageAreaList.size(); i++) {
            try {
                PageArea pageArea = pageAreaList.get(i);
                logger.info("抽取{}章有息债务业务模型数据，当前页码：{}，表格区域：{}。", getChapterModel().getChapterId(), pageArea.getPageNumber(), pageArea.getLayout());
                List<String> pageTableDataList = extractPdfByTable(new String[]{getDocumentModel().getPdfFilePath(), "-l", "-p", String.valueOf(pageArea.getPageNumber()), "-a", pageArea.getLayout(), "-f", "JSON"});
                logger.info("抽取{}章有息债务业务模型数据，当前页码：{}，表格数量：{}，表格数据：{}。", getChapterModel().getChapterId(), pageArea.getPageNumber(), pageTableDataList.size(), pageTableDataList);
                if (pageTableDataList.isEmpty()) {
                    continue;
                }
                String tableHeader = pageTableDataList.get(0);
                List<YXZWIndex> yxzwIndexList = new ArrayList<>();
                logger.info("抽取{}章有息债务业务模型数据，表头信息：{}。", getChapterModel().getChapterId(), tableHeader);
                JsonArray pageDataJsonArray = str2Json(tableHeader).getAsJsonArray();
                JsonObject pataTableData = pageDataJsonArray.get(0).getAsJsonObject();
                JsonArray items = pataTableData.get("data").getAsJsonArray();
                JsonArray itemArray = items.get(0).getAsJsonArray();
                for (int j = 0; j < itemArray.size(); j++) {
                    JsonObject cell = itemArray.get(j).getAsJsonObject();
                    String text = cell.get("text").getAsString().trim();
                    if (isEmpty(text)) {
                        continue;
                    }
                    text = replaceCRLF(text);
                    //TODO 先这么着吧，后面再改吧
                    //20181211已修改完毕
                    ExtractItem extractItem = yxzwTokenizer.splitWords(extractBizModel, text);
                    if (extractItem != null) {
                        yxzwIndexList.add(new YXZWIndex(extractItem.getItemName(), Integer.valueOf(j)));
                    }
                }
                for (int j = 0; j < pageTableDataList.size(); j++) {
                    String tableData = pageTableDataList.get(j);
                    logger.info("抽取{}章有息债务业务模型数据，表格数据：{}。", getChapterModel().getChapterId(), tableData);
                    JsonArray pageData = str2Json(tableData).getAsJsonArray();
                    JsonObject var1 = pageData.get(0).getAsJsonObject();
                    JsonArray var2 = var1.get("data").getAsJsonArray();
                    for (int l = 0; l < var2.size(); l++) {
                        if (l < 1) {
                            continue;
                        }
                        JsonArray var3 = var2.get(l).getAsJsonArray();
                        try {
                            Map<String, ExtractItem> yxzwItems = new HashMap<>();
                            for (int k = 0; k < yxzwIndexList.size(); k++) {
                                logger.info("抽取{}章有息债务业务模型数据，第{}页，第{}条数据，内容：{}。", getChapterModel().getChapterId(), i, j, var3.toString());
                                YXZWIndex yxzwIndex = yxzwIndexList.get(k);
                                JsonElement jsonElement = var3.get(yxzwIndex.getIndex()).getAsJsonObject();
                                String text = ((JsonObject) jsonElement).get("text").getAsString();
                                if (isEmpty(text)) {
                                    continue;
                                }
                                ExtractItem extractItem = extractBizModel.getExtractItem(yxzwIndex.getName());
                                ExtractItem newExtractItem = (ExtractItem) BeanUtils.cloneBean(extractItem);
                                setKV(newExtractItem, jsonElement, jsonElement);
                                yxzwItems.put(newExtractItem.getItemName(), newExtractItem);
                                logger.info("抽取{}章有息债务业务模型数据，数据内容：{}。", getChapterModel().getChapterId(), var3.toString());
                            }
                            if (yxzwItems.isEmpty()) {
                                continue;
                            }
                            extractBizModel.addTable3(yxzwItems);
                        } catch (IllegalAccessException e) {
                            logger.error(e.getMessage(), e);
                        } catch (InstantiationException e) {
                            logger.error(e.getMessage(), e);
                        } catch (InvocationTargetException e) {
                            logger.error(e.getMessage(), e);
                        } catch (NoSuchMethodException e) {
                            logger.error(e.getMessage(), e);
                        }
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        yxzwTokenizer.unloadCoreSynonyms(extractBizModel);
        logger.info("抽取{}章有息债务业务模型数据，数据结构：{}。", getChapterModel().getChapterId(), obj2Json(extractBizModel));
        long t2 = System.currentTimeMillis();
        logger.info("抽取{}章有息债务业务模型数据，耗时：{}毫秒。", getChapterModel().getChapterId(), (t2 - t1));
    }

    private void extractM4Mjzjyt() {
        long t1 = System.currentTimeMillis();
        logger.info("开始抽取{}章募集资金用途业务模型数据......", getChapterModel().getChapterId());
        ExtractBizModel extractBizModel = getChapterModel().getExtractBizModelMap().get("MJZJYT");
        ExtractItem targetExtractItem = null;
        List<PageModel> pageModelList = getChapterModel().getPageModelList();
        PageModel pageModel = null;
        mjzjytTokenizer.loadCoreSynonyms(extractBizModel);
        List<SectionModel> sectionModelList = getChapterModel().getSectionModelList();
        for (int i = 0; i < sectionModelList.size(); i++) {
            SectionModel sectionModel = sectionModelList.get(i);
            if (sectionModel == null) {
                continue;
            }
            //二级标题
            targetExtractItem = mjzjytTokenizer.splitWords(extractBizModel, sectionModel);
            if (targetExtractItem != null) {
                logger.info("抽取{}章募集资金用途业务模型，分析到募集资金用途，模型名称：{}。", getChapterModel().getChapterId(), targetExtractItem.getItemName());
                TextLayout kTextLayout = cloneTextLayout(sectionModel.getTextLayout());
                kTextLayout.setText(sectionModel.getTitle());
                TextLayout vTextLayout = cloneTextLayout(sectionModel.getTextLayout());
                targetExtractItem.getKey().add(kTextLayout);
                targetExtractItem.getValue().add(vTextLayout);
                extractBizModel.getExtractItem(MJZJYTModel.MODEL_NAME).setKey(targetExtractItem.getKey());
                extractBizModel.getExtractItem(MJZJYTModel.MODEL_NAME).setValue(targetExtractItem.getValue());
                break;
            }
        }
        if (targetExtractItem == null) {
            return;
        }
        if (targetExtractItem.getKey() == null) {
            return;
        }

        MJZJYTType mjzjytType = MJZJYTType.valueOf(targetExtractItem.getKey().getText());
        if (mjzjytType == null) {
            logger.error("未能分析到募集资金用途！！！");
            return;
        }
        switch (mjzjytType) {
            case YXZW:
            case YHJK:
                extractM4Yxzw2();
                break;
            case XMJS:
                break;
            case BCXMZBJ:
                break;
        }
        mjzjytTokenizer.unloadCoreSynonyms(extractBizModel);
        long t2 = System.currentTimeMillis();
        logger.info("抽取{}章募集资金用途业务模型数据完成，耗时：{}毫秒。", getChapterModel().getChapterId(), (t2 - t1));
    }
}

class YXZWIndex {
    String name;
    int index;

    public YXZWIndex(String name, int index) {
        this.name = name;
        this.index = index;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }
}
